﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Web;
using System.Windows;
using System.Windows.Forms;

namespace hkgoldenhighlight
{
	public partial class SettingsForm : Form
	{
		private static bool ExceptionOccuredBefore = false;
		private static Exception generalEx = new Exception();
		internal static string ReleasedVersion = "0.0.0.0";
		internal static string SaveType = "*.ini";
		
		public SettingsForm()
	    {
	        this.InitializeComponent();
	    }
		
		#region Links
	    private void Auman311LinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.auman311LinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=278779");
	    }
	
	    private void BkLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.bkLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=245639");
	    }
	
	    private void BmggmLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.bmggmLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=230828");
	    }
	    
	    private void FanyungLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.fanyungLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=247231");
	    }
	
	    private void FirefoxyLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.FirefoxyLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=147853");
	    }
	
	    private void FtgbLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.ljwgLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=226503");
	    }
	
	    private void GnfgLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.gnfgLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=219751");
	    }
	
	    private void HKGSherlockLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.HKGSherlockLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=229020");
	    }
	
	    private void hsdnhLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.hsdnhLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=133042");
	    }
	
	    private void Jay_SongLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.Jay_SongLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=147853");
	    }
	
	    private void JdsnyLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.jdsnyLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=231268");
	    }
	
	    private void K_kelLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.k_kelLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=250846");
	    }
	
	    private void LjwgLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.ljwgLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=217217");
	    }
	
	    private void LtmsyLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.ltmsyLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=205216");
	    }
	
	    private void NhsgpLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.ljwgLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=247641");
	    }
	
	    private void PnutsLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.pnutsLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=140415");
	    }
	    
	    private void RefLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.ljwgLinkLabel.LinkVisited = true;
	        Process.Start("http://www.harding.edu/fmccown/screensaver/screensaver.html");
	    }
	
	    private void ReturnLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.ljwgLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=170434");
	    }
	
	    private void SbdLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.sbdLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=254851");
	    }
	
	    private void SimpsonsLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.SimpsonsLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=271629");
	    }
	
	    private void SulphateLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.SulphateLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=250169");
	    }
	
	    private void TdysLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.tdysLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=266634");
	    }
	
	    private void Theo_WalcottLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.Theo_WalcottLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=228386");
	    }
	
	    private void TsingSamLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
	    {
	        this.TsingSamLinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/ProfilePage.aspx?userid=250846");
	    }
	    
	    	private void DhyjLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			this.auman311LinkLabel.LinkVisited = true;
	        Process.Start("http://forum1.hkgolden.com/images/bb_bookmarks/profile.gif");
		}
		
		private void EvchkArticleLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			this.auman311LinkLabel.LinkVisited = true;
	        Process.Start("http://evchk.wikia.com/wiki/%E9%AB%98%E7%99%BB%E8%81%96%E8%AA%95%E5%9C%96");
		}
		
		private void CodeGoogleComLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			this.auman311LinkLabel.LinkVisited = true;
	        Process.Start("http://code.google.com/p/hkgoldenhighlight/");
		}
		
		private void GNUGPLv3LinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			this.auman311LinkLabel.LinkVisited = true;
			Process.Start("http://www.gnu.org/licenses/gpl.html");
		}
	    #endregion
		
	    private int CheckIfItsANewestVersion(BackgroundWorker bw, int delayms)
	    {
	    	int result = new Int32();
	    	
	        if (ExceptionOccuredBefore)
	        {
	            this.updateButton.Visible = true;
	            this.recheckButton.Visible = this.recheckButton.Enabled = false;
	            ExceptionOccuredBefore = false;
	        }
	        this.updateButton.Enabled = false;
	        this.updateTextLabel.Text = "檢查版本中……";
	        this.loadingUpdatePictureBox.Visible = true;
	        this.goodUpdatePictureBox.Visible = false;
	        this.deadUpdatePictureBox.Visible = false;
	        this.winkUpdatePictureBox.Visible = false;
	        try
	        {
	            // download information
				byte[] Data = new byte[4096]; int Length = 0;
				using (System.Net.WebClient Client = new System.Net.WebClient()) {
					using (System.IO.Stream Stream = Client.OpenRead("http://hkgoldenhighlight.googlecode.com/svn/trunk/hkgoldenhighlight/version.txt")) {
						while (true) {
							if (Length + 256 >= Data.Length) Array.Resize<byte>(ref Data, Data.Length << 1);
							int n = Stream.Read(Data, Length, 256);
							if (n != 0) {
								Length += n;
							} else break;
						}
						Stream.Close();
					}
				}
				Array.Resize<byte>(ref Data, Length);
				// parse information
				System.Text.Encoding Encoding = new System.Text.UTF8Encoding();
				string Text = new string(Encoding.GetChars(Data));
				if (Text.Length != 0 && Text[0] == '\uFEFF') Text = Text.Substring(1);
				string[] Lines = Text.Split(new char[] { '\r', '\n' });
				if (Lines.Length == 0 || !Lines[0].Equals("$hkgoldenhighlight", StringComparison.OrdinalIgnoreCase))
	            {
					throw new Exception("更新資訊檔損壞。");
	            }
	            else
	            {
	                for (int i = 1; i < Lines.Length; i++)
	                {
	                    int h = Lines[i].IndexOf('=');
	                    if (h >= 0)
	                    {
	                        string a = Lines[i].Substring(0, h).TrimEnd(new char[0]);
	                        string b = Lines[i].Substring(h + 1).TrimStart(new char[0]);
	                        if (a.Equals("version", StringComparison.OrdinalIgnoreCase))
	                        {
	                            ReleasedVersion = b;
	                        }
	                    }
	                }
	                
	                
	                if (this.CompareVersion(Application.ProductVersion, ReleasedVersion))
	                    result = 2;
	                else
						result = 1;
	            }
	        }
	        catch (Exception ex)
	        {
	            generalEx = ex;
	            result = 3;
	        }
	        
	        return result;
	    }
	
	    private bool CompareVersion(string curversion, string newversion)
	    {
	    	int m;
	        int[] curv = new int[0];
	        int[] newv = new int[0];
	        int jj = 0;
	        for (int i = 0; i < curversion.Length; i++)
	        {
	            int j = curversion.IndexOf('.', jj);
	            if (j >= 0)
	            {
	                Array.Resize<int>(ref curv, curv.Length + 1);
	                curv[i] = Convert.ToInt32(curversion.Substring(0, j).TrimEnd(new char[0]));
	                curversion = curversion.Substring(j + 1).TrimStart(new char[0]);
	                jj++;
	            }
	        }
	        if (curversion.Length != 0)
	        {
	            Array.Resize<int>(ref curv, curv.Length + 1);
	            curv[jj] = Convert.ToInt32(curversion);
	        }
	        int lm = 0;
	        for (int k = 0; k < newversion.Length; k++)
	        {
	            int l = newversion.IndexOf('.', lm);
	            if (l >= 0)
	            {
	                Array.Resize<int>(ref newv, newv.Length + 1);
	                newv[lm] = Convert.ToInt32(newversion.Substring(0, l).TrimEnd(new char[0]));
	                newversion = newversion.Substring(l + 1).TrimStart(new char[0]);
	                lm++;
	            }
	        }
	        if (newversion.Length != 0)
	        {
	            Array.Resize<int>(ref newv, newv.Length + 1);
	            newv[lm] = Convert.ToInt32(newversion);
	        }
	        if (curv.Length > newv.Length)
	        {
	            m = newv.Length - 1; //the last code is the build no, no need to check
	        }
	        else
	        {
	            m = curv.Length - 1; //the last code is the build no, no need to check
	        }
	        int n; for (n = 0; n < m; n++)
	        {
	            if (curv[n] < newv[n])
	            {
	                return true; //need to update
	            }
	        }
	        return false; //no need to update
	    }
		
		private void CheckNewBackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
		{
			// Do not access the form's BackgroundWorker reference directly.
            // Instead, use the reference provided by the sender parameter.
            BackgroundWorker bw = sender as BackgroundWorker;

            // Extract the argument.
            //int arg = (int)e.Argument;
            
            // Start the time-consuming operation.
            e.Result = CheckIfItsANewestVersion(bw, 0);
		}
		
		private void CheckNewBackgroundWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			/*
			 * 0: Cancelled
			 * 1: Succeed and this is the newest version
			 * 2: Succeed and this may need to be updated
			 * 3: Failed with error(s)
			 */
			switch ((int)e.Result) {
				case 0:
				{
					//TODO
					break;
				}
				case 1: 
				{
					this.updateTextLabel.Text = "此程式已經是最新版（" + Application.ProductVersion + "）！";
                    this.loadingUpdatePictureBox.Visible = false;
                    this.goodUpdatePictureBox.Visible = true;
                    this.deadUpdatePictureBox.Visible = false;
                    this.winkUpdatePictureBox.Visible = false;
                    this.loadingUpdatePictureBox.Visible = false;
					break;
				}
				case 2:
				{
					this.updateTextLabel.Text = "此程式的最新版（" + ReleasedVersion + "）已經發佈！";
	                this.loadingUpdatePictureBox.Visible = false;
	                this.goodUpdatePictureBox.Visible = false;
	                this.deadUpdatePictureBox.Visible = false;
	                this.winkUpdatePictureBox.Visible = true;
	                this.updateButton.Enabled = true;
	                this.loadingUpdatePictureBox.Visible = false;
					break;
				}
				case 3:
				{
					this.updateTextLabel.Text = "在檢查期間發生錯誤：" + generalEx.Message;
		            this.loadingUpdatePictureBox.Visible = false;
		            this.goodUpdatePictureBox.Visible = false;
		            this.deadUpdatePictureBox.Visible = true;
		            this.winkUpdatePictureBox.Visible = false;
		            this.updateButton.Visible = false;
		            this.recheckButton.Visible = this.recheckButton.Enabled = true;
		            ExceptionOccuredBefore = true;
					break;
				}
				default:
				{
					//???
					break;
				}
			}
		}
		
	    private void SettingsFormLoad(object sender, EventArgs e)
	    {
	    	this.Text = this.Text.Replace("{Version}", Application.ProductVersion);
	    	this.CheckNewBackgroundWorker.RunWorkerAsync();
	    	
	    	InfFile.LoadFromInfFile();
	    }
		
		private void UpdateButtonClick(object sender, EventArgs e)
		{
			UpdaterDownloadForm updateDialog = new UpdaterDownloadForm();
			
			updateDialog.ShowDialog(this);
		}
		
		private void SiteLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			this.auman311LinkLabel.LinkVisited = true;
	        Process.Start("http://xmas.hkgolden.com/");
		}
		
		private void MultiMonSetButtonClick(object sender, EventArgs e)
		{
			multiMonSettingsForm mMonDialog = new multiMonSettingsForm();
			
			mMonDialog.ShowDialog(this);
		}
		
		private void BackgroundMusicSetButtonClick(object sender, EventArgs e)
		{
			BackgroundMusic BGMDialog = new BackgroundMusic();
			
			BGMDialog.ShowDialog(this);
		}
	}
}